import {
  app,
  session,
  shell,
  BrowserWindow,
  ipcMain,
  nativeTheme,
  Menu,
  Tray,
  Notification,
  globalShortcut,
  dialog,
  nativeImage,
  screen,
  desktopCapturer,
  clipboard
} from 'electron'
import path, { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import fs from 'fs'

electronApp.setAppUserModelId('cn.lixuan.fun')

function registerShortCuts() {
  globalShortcut.register('CommandOrControl+Shift+i', () => {
    mainWindow.webContents.openDevTools()
  })

  globalShortcut.register('Esc', () => {
    mainWindow.close()
  })
}
let tray
function updateCheck() {
  const options = {
    icon: 'src/assets/icon.ico',
    title: '温馨提示',
    body: '发现新版本，点击立即更新'
  }
  const notify = new Notification(options)
  notify.show()
  notify.on('click', () => {
    console.log(111)
  })
}

function createTray() {
  const template = [
    {
      label: '检查更新',
      click: updateCheck
    },
    {
      label: '退出',
      click: () => {
        mainWindow.destroy()
        app.quit()
      }
    }
  ]

  tray = new Tray('src/assets/icon.ico')
  tray.setToolTip('demo')

  const menu = Menu.buildFromTemplate(template)
  tray.setContextMenu(menu)

  tray.on('click', () => {
    mainWindow.show()
  })
}

function flushTray() {
  let flag = false
  setInterval(() => {
    flag ? tray.setImage(nativeImage.createEmpty()) : tray.setImage('src/assets/icon.ico')
    flag = !flag
  }, 500)
}

function createAppicationMenu() {
  const template = [
    {
      label: '管理中心'
    },
    {
      label: '人员管理'
    },
    {
      label: '系统管理',
      submenu: [
        {
          label: '浅色主题',
          click: () => {
            nativeTheme.themeSource = 'light'
          }
        },
        {
          label: '深色主题',
          click: () => {
            nativeTheme.themeSource = 'dark'
          }
        },
        {
          label: '跟随系统',
          click: () => {
            nativeTheme.themeSource = 'system'
          }
        }
      ]
    },
    {
      label: '关于我们'
    }
  ]
  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

let mainWindow
let loadingWindow
let captureWindow

function createWindow(options, callback, path = '', url = '../renderer/index.html') {
  const defaultOptions = {
    width: 800,
    height: 600,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  }
  const win = new BrowserWindow({ ...defaultOptions, ...options })

  win.loadFile(join(__dirname, url))

  // win.webContents.openDevTools()

  if (path) {
    win.webContents.on('did-finish-load', () => {
      win.webContents.send('router-push', path)
    })

    ipcMain.on('router-finish', (e, data) => {
      callback && callback(win)
    })
  }

  return win
}

async function createCaptureWindow() {
  const {
    bounds: { width, height },
    scaleFactor
  } = screen.getPrimaryDisplay()

  const sources = await desktopCapturer.getSources({
    types: ['screen'],
    thumbnailSize: {
      width: width * scaleFactor,
      height: height * scaleFactor
    }
  })

  const base64 = sources[0].thumbnail.toDataURL()

  captureWindow = createWindow(
    {
      fullscreen: true,
      transparent: true,
      frame: false,
      skipTaskbar: true,
      autoHideMenuBar: true,
      moveable: false,
      resizable: false,
      enableLargerThanScreen: true,
      hasShadow: false,
      show: false
    },
    (win) => {
      if (captureWindow === win) {
        win.webContents.send('capture-on', base64)
        setTimeout(() => {
          win.show()
        }, 100)
      }
    },
    '/capture'
  )

  captureWindow.on('closed', () => {
    captureWindow = null
    mainWindow.show()
    globalShortcut.unregister('Esc')
  })

  globalShortcut.register('Esc', () => {
    captureWindow.close()
  })
}

function createLoadingWindow() {
  loadingWindow = createWindow({
    width: 400,
    height: 300,
    frame: false
  })
}

function createMainWindow() {
  mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    // frame: false,
    // autoHideMenuBar: true,
    // ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  nativeTheme.themeSource = 'light'

  // mainWindow.on('ready-to-show', () => {
  //   mainWindow.show()
  // })

  mainWindow.on('close', (e) => {
    e.preventDefault()
    mainWindow.hide()
  })

  mainWindow.on('closed', () => {
    mainWindow = null
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

app.whenReady().then(() => {
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  ipcMain.on('ping', () => console.log('pong'))

  createMainWindow()
  createLoadingWindow()
  createAppicationMenu()
  createTray()
  // flushTray()
  registerShortCuts()

  // session.defaultSession.loadExtension(path.resolve(__dirname, '../../resources/vue-devtools'))

  // C:\Users\gaoha\Desktop\vue-devtools
  // session.defaultSession.loadExtension('C:\\Users\\gaoha\\Desktop\\vue-devtools')

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) {
      createMainWindow()
    }
  })

  app.on('will-quit', () => {
    globalShortcut.unregisterAll()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

ipcMain.on('set-title', (e, title) => {
  mainWindow.setTitle(title)
})

ipcMain.handle('window-state', (e, action) => {
  switch (action) {
    case 'min':
      mainWindow.minimize()
      break
    case 'max':
      mainWindow.isMaximized() ? mainWindow.unmaximize() : mainWindow.maximize()
      break
    case 'close':
      mainWindow.close()
      break
    default:
      break
  }

  return mainWindow.isMaximized()
})

ipcMain.handle('dark-mode', (e, target) => {
  nativeTheme.themeSource = target || (nativeTheme.shouldUseDarkColors ? 'light' : 'dark')
  return nativeTheme.shouldUseDarkColors
})

ipcMain.handle('get-window-pos', () => {
  return mainWindow.getBounds()
})

ipcMain.on('set-window-pos', (e, pos) => {
  mainWindow.setBounds({ ...pos, width: 900, height: 670 })
})

ipcMain.on('menu:context', (e, type) => {
  const template =
    type === 'side'
      ? [
          {
            label: '复制'
          },
          {
            label: '刷新'
          }
        ]
      : [
          {
            label: '右边菜单'
          }
        ]

  const menu = Menu.buildFromTemplate(template)
  menu.popup({ window: BrowserWindow.fromWebContents(e.sender) })
})

ipcMain.handle('dialog:message', (e, options) => {
  const win = BrowserWindow.fromWebContents(e.sender)

  return dialog.showMessageBox(win, options)
})

ipcMain.handle('dialog:open-file', (e, options) => {
  const win = BrowserWindow.fromWebContents(e.sender)
  return dialog.showOpenDialog(win, options)
})

ipcMain.handle('dialog:save-file', (e, options) => {
  const win = BrowserWindow.fromWebContents(e.sender)
  return dialog.showSaveDialog(win, options)
})

ipcMain.handle('fs:read-file', (e, filePath) => {
  return fs.promises.readFile(filePath, 'utf-8')
})

ipcMain.handle('fs:write-file', (e, options) => {
  const { filePath, fileContent } = options
  return fs.promises.writeFile(filePath, fileContent, 'utf-8')
})

ipcMain.handle('capture:open', () => {
  mainWindow.hide()

  createCaptureWindow()
})

ipcMain.handle('capture-off', () => {
  captureWindow.close()
})

ipcMain.handle('capture-save', (e, base64) => {
  const img = nativeImage.createFromDataURL(base64)
  clipboard.writeImage(img)
  captureWindow.close()
})

ipcMain.once('loading:done', () => {
  loadingWindow.destroy()
  mainWindow.show()
})
